<?php

namespace app\award;

use app\models\NewLevel;
use app\models\order\Order;
use app\models\order\OrderItem;
use app\models\product\ProductArea;
use app\models\SetUserUp;
use app\models\user\User;
use app\models\user\UserLevel;
use app\services\Chain;

class Up
{
    protected $order;
    protected $user;
    protected $set;

    public function __construct(Order $order)
    {
        $this->order = $order;
        $this->user = User::findOne(['id' => $this->order->user_id]);

        $first_order_item = OrderItem::find()
            ->where(['order_id' => $order->id])
            ->orderBy(['id' => SORT_ASC])
            ->limit(1)
            ->one();
        $product_id = $first_order_item->product_id;

        $is_bao = ProductArea::checkBao($product_id);
        $is_diff = ProductArea::checkDiff($product_id);

        $this->set = SetUserUp::getLastOne();

        // 必须是报单区
        if ($is_bao) {
            $this->upMyself();
        }

        // 差价升级
        if ($is_diff) {
            $this->upDiff();
        }

    }

    // 升级自己
    protected function upMyself()
    {
        $user = $this->user;

        $amount = $this->order->total_pay - $this->order->total_freight;

        if ($amount >= $this->set->vip2) {
            if ($user->level < UserLevel::$keys['vip2']) {
                $user->level = UserLevel::$keys['vip2'];
                $user->save();

                // 配额
                self::addVip1($user, $this->set->num);
            }
        }

        if ($amount >= $this->set->vip1) {
            if ($user->level < UserLevel::$keys['vip1']) {
                $user->level = UserLevel::$keys['vip1'];
                $user->save();
            }
        }

    }

    // 差价升级
    protected function upDiff()
    {
        $user = $this->user;

        $amount = $this->order->total_pay - $this->order->total_freight;

        if ($amount == $this->set->diff) {
            if ($user->level < UserLevel::$keys['vip2']) {
                $user->level = UserLevel::$keys['vip2'];
                $user->save();

                self::addVip1($user, $this->set->num);
            }
        }
    }

    // 配额
    public static function addVip1(User $user, $num)
    {
        $user->vip1_num += $num;
        $user->save();
    }

}